/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> v;

        if (root == nullptr) return v;

        queue<TreeNode*> q;
        q.push(root);

        while (q.size())
        {
            vector<int> level;
            int size = q.size();
            while (size > 0)
            {
                auto t = q.front(); q.pop();

                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);

                level.push_back(t->val);
                --size;
            }

            v.push_back(level);
        }

        return v;
    }
};